import { Logger } from '../../utils/logger';
import { BrowserUtils } from '~/utils/browser';
import { iDocUrlRegex } from '~/utils/idoc';

const LUR_Cache = new Map<string, any>();

// 从当前iDoc的App的全部数据中查找指定设计ID的页面数据
function findPageDataFormAppDesignData(appData, designId: string) {
  const { pages } = appData.payload;

  for (let i = 0; i < pages.length; i++) {
    const { children } = pages[i];

    if (children && children.length > 0) {
      for (const child of children) {
        if (child._id === designId) {
          return child;
        }
      }
    }
  }

  return null;
}

/** 从设计图中抓取数据 */
export async function captureDataFromUrl(url: string): Promise<any> {
  const { appId, designId } = iDocUrlRegex(url);

  const cacheKey = `${appId}-${designId}`;

  if (LUR_Cache.has(cacheKey)) {
    Logger.info(`使用缓存数据: ${cacheKey}`);

    return JSON.parse(LUR_Cache.get(cacheKey));
  }

  const startTime = Date.now();

  const result = await BrowserUtils.waitForApiData(url, `/app/module/${appId}/design`);

  if (!result) {
    Logger.error(`无法获取设计图数据: ${url}`);

    return null;
  }

  const pageData = findPageDataFormAppDesignData(result.data, designId);

  const pageJsonData = await (await result.utils.waitForResponse(pageData.dataURL)).json();

  Logger.info(`设计图捕获成功: ${designId} (${Date.now() - startTime}ms)`);

  result.utils.close();

  LUR_Cache.set(cacheKey, JSON.stringify(pageJsonData));

  return pageJsonData;
}
